<template>
  <div class="box">
    <h2>创建任务</h2>
    <el-input v-model="data.summary"
              placeholder="请输入标题"
              size="normal"
              clearable
              class="title"></el-input>
    <el-input v-model="data.description"
              placeholder="请输入内容"
              :rows="2"
              type="textarea"
              class="content"></el-input>
    <div class="time">
      <text>截止时间 </text>
      <el-date-picker v-model="time"
                      type="date"
                      placeholder="选择"
                      size="default"
                      @change="sendtime"
                      :disabled-date="disabledDate" />
    </div>
    <el-button type="primary"
               size="default"
               @click="sendtask">立即发送</el-button>
    <router-link to="./"
                 class="sendmsg">点我去发送消息</router-link>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter } from 'vue-router'
import { getid, sendTask } from '../api/api'
const router = useRouter()
const time = ref(new Date())
const data = reactive({
  // 标题
  summary: "",
  // 内容
  description: "",
  due: {
    // 截止日期
    time: Math.round(new Date().getTime() / 1000)
  },
  // 来源
  origin: {
    "platform_i18n_name": "{\"zh_cn\": \"IT 工作台\", \"en_us\": \"IT Workspace\"}"
  },
  // 能否编辑
  can_edit: true,
  // 关注者id
  follower_ids: [
  ],
  // 创建者id
  collaborator_ids: [
  ]
})

// 把时间戳转换为unix格式
const sendtime = () => {
  data.due.time = Math.round(time.value.getTime() / 1000)
}

// 获取用户open_id
const getId = async () => {
  const phone = localStorage.getItem('phone')
  if (phone == null) {
    ElMessage.error('请重新登录')
    router.push('./login')
  } else {
    await getid({ phone: phone }).then(res => {
      let id = res.data.data.user_list[0].user_id
      data.follower_ids[0] = id
      data.collaborator_ids[0] = id
    })
  }
}

const sendtask = async () => {
  await getId().then((res) => {
    if (data.summary && data.description) {
      sendTask(data)
      ElMessage.success('创建成功')
    } else {
      ElMessage.error('请输入内容')
    }
  })
}

// 禁止点击当前日期之前的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
}

</script>
<style scoped lang="less">
.box {
  width: 50%;
  height: 200px;
  margin: 100px auto;
  .title {
    margin: 10px 0;
  }
  .content {
    margin: 10px 0;
  }
  .time {
    transform: translateX(-25%);
    margin: 20px 0;
  }
  .sendmsg {
    text-decoration: none;
    margin-left: 100px;
    color: #409eff;
  }
}
</style>